package bookshop.service;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bookshop.util.JwtUtil;

public class LoginService {
	public String getToken(String user) {
		String cookieValue = new JwtUtil(user.toString(),null).creatJwt();
		return cookieValue;
	}
	
	public boolean checkCookie(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies=request.getCookies();
		if(cookies!=null&&cookies.length>0) {
			for(Cookie cookie:cookies) {
				if("bookTicket".equals(cookie.getName())){
					String token=(String) request.getSession().getAttribute(cookie.getValue());				
					boolean isok= new JwtUtil(null,token).freeJwt();
					if(isok) {
						return true;
					}
				}
			}
		}
		return false;
	}
	public void setCookieSession(HttpServletRequest request,HttpServletResponse response,String name ) {
		String token=getToken(name);
		String st=(new Date()).getTime()+"";
		Cookie tokenCookie=new Cookie("bookTicket",st);
		response.addCookie(tokenCookie);
		request.getSession().setAttribute(st, token);
		request.getSession().setAttribute("bookTicket", st);
	}
	public void loginOut(HttpServletRequest request,HttpServletResponse response) {
		HttpSession session=request.getSession();
		session.removeAttribute((String) session.getAttribute("bookTicket"));
		session.removeAttribute("bookTicket");
		Cookie rcookie = new Cookie("bookTicket",null);//cookie名字要相同
		rcookie.setMaxAge(0); //
		rcookie.setPath(request.getContextPath());  // 相同路径
		response.addCookie(rcookie);
		rcookie.setMaxAge(0);			
	}
}
